Public Class formMain
    Private ChInfo As wowcrawler.CharactersInfo

    Private Regions() As String
    Private Realms() As String
    Private Guilds() As String
    Private Charas() As String

    Private CurrentChara As WowCrawler.CharactersInfo.Characters = Nothing

    Private GUI_UPDATING As Boolean = False

    Private RosterFolder As String = ""
    Private RosterRaidVersionFilter As Double

    Private Sub formMain_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        WriteSetup()
    End Sub

    Private Sub formMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim armory As New WowCrawler.AccessArmory
        Regions = armory.RegionString

        SplitContainer1.Dock = DockStyle.Fill
        WebBrowser1.Dock = DockStyle.Fill
        TabControl1.Dock = DockStyle.Fill
        TabControl1.TabIndex = 0

        ToolStripStatusLabel1.Text = ""
        ToolStripStatusLabel_Crawl.Text = ""

        ChInfo = New WowCrawler.CharactersInfo

        GUI_UPDATING = True
        Dim i As Integer
        textRegion.Items.Clear()
        For i = 0 To Regions.Length - 1
            textRegion.Items.Add(Regions(i))
        Next
        textRegion.Text = armory.GetRegionString(WowCrawler.AccessArmory.RegionType.US)
        filterLevel.Text = "80"
        textUpdateInterval.Text = ChInfo.UpdateInterval.ToString
        GUI_UPDATING = False

        RosterFolder = My.Computer.FileSystem.CombinePath(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "WoW Roster")
        RosterRaidVersionFilter = 3.0

        ReadSetup()
    End Sub

    Private Sub ReadSetup()
        Dim XmlDoc As New Xml.XmlDocument
        Try
            XmlDoc.Load(My.Computer.FileSystem.CombinePath(My.Computer.FileSystem.SpecialDirectories.CurrentUserApplicationData, "setup.xml"))
        Catch ex As Exception
            Exit Sub
        End Try

        Dim node As Xml.XmlElement
        GUI_UPDATING = True
        For Each node In XmlDoc.SelectNodes("BlueForestSetup/Setting")
            Try
                If node.GetAttribute("simple") = "1" Then
                    chkSimpleText.Checked = True
                Else
                    chkSimpleText.Checked = False
                End If
            Catch ex As Exception
            End Try
        Next
        For Each node In XmlDoc.SelectNodes("BlueForestSetup/Filter")
            Try
                textRegion.Text = node.GetAttribute("region")
            Catch ex As Exception
            End Try

            Try
                textRealm.Text = node.GetAttribute("realm")
            Catch ex As Exception
            End Try

            Try
                textGuild.Text = node.GetAttribute("guild")
            Catch ex As Exception
            End Try

            Try
                filterClass.Text = node.GetAttribute("class")
            Catch ex As Exception
            End Try

            Try
                filterLevel.Text = node.GetAttribute("level")
            Catch ex As Exception
            End Try

            Try
                textUpdateInterval.Text = node.GetAttribute("interval")
            Catch ex As Exception
            End Try

            Try
                GUI_UPDATING = False
                textCharacter.Text = node.GetAttribute("name")
                GUI_UPDATING = True
            Catch ex As Exception
            End Try
        Next

        For Each node In XmlDoc.SelectNodes("BlueForestSetup/Roster")
            Try
                RosterFolder = node.GetAttribute("path")
            Catch ex As Exception
            End Try

            Try
                RosterRaidVersionFilter = node.GetAttribute("verFilter")
            Catch ex As Exception
            End Try
        Next

        GUI_UPDATING = False
    End Sub

    Private Sub WriteSetup()
        Dim Xml As String = ""

        Xml &= "<BlueForestSetup>"
        Xml &= vbCrLf

        Xml &= "<Setting simple="""
        If chkSimpleText.Checked Then
            Xml &= "1"
        Else
            Xml &= "0"
        End If
        Xml &= """/>"
        Xml &= vbCrLf

        Xml &= "<Filter region=""" & textRegion.Text & """"
        Xml &= " realm=""" & textRealm.Text & """"
        Xml &= " guild=""" & textGuild.Text & """"
        Xml &= " class=""" & filterClass.Text & """"
        Xml &= " name=""" & textCharacter.Text & """"
        Xml &= " level=""" & filterLevel.Text & """"
        Xml &= " interval=""" & textUpdateInterval.Text & """"
        Xml &= "/>"
        Xml &= vbCrLf

        Xml &= "<Roster"
        Xml &= " path=""" & RosterFolder & """"
        Xml &= " verFilter=""" & RosterRaidVersionFilter & """"
        Xml &= "/>"
        Xml &= vbCrLf

        Xml &= "</BlueForestSetup>"
        Xml &= vbCrLf

        Dim XmlDoc As New Xml.XmlDocument
        Try
            XmlDoc.LoadXml(Xml)
            XmlDoc.Save(My.Computer.FileSystem.CombinePath(My.Computer.FileSystem.SpecialDirectories.CurrentUserApplicationData, "setup.xml"))
        Catch ex As Exception

        End Try
    End Sub

    Private Sub UpdateRealms(ByVal Region As String)
        Dim ct = 0
        Dim i As Long
        For i = 0 To ChInfo.Chara.Length - 1
            If ChInfo.Chara(i).Region = Region Then
                Dim j As Integer
                Dim exist As Boolean = False

                For j = 0 To ct - 1
                    If Realms(j) = ChInfo.Chara(i).Realm Then
                        exist = True
                        Exit For
                    End If
                Next

                If exist Then
                Else
                    ReDim Preserve Realms(ct)
                    Realms(ct) = ChInfo.Chara(i).Realm
                    ct += 1
                End If
            End If
        Next

        textRealm.Items.Clear()
        For i = 0 To ct - 1
            textRealm.Items.Add(Realms(i))
        Next
        If textRealm.Items.Count > 0 Then
            textRealm.SelectedIndex = 0
        Else
            textRealm.Text = ""
            UpdateGuilds("", Region)
        End If
    End Sub

    Private Sub UpdateGuilds(ByVal Realm As String, ByVal Region As String)
        Dim ct = 0
        Dim i As Long
        For i = 0 To ChInfo.Chara.Length - 1
            If ChInfo.Chara(i).Region = Region And (ChInfo.Chara(i).Realm = Realm Or Realm = "") Then
                Dim j As Integer
                Dim exist As Boolean = False

                For j = 0 To ct - 1
                    If Guilds(j) = ChInfo.Chara(i).Guild Then
                        exist = True
                        Exit For
                    End If
                Next

                If exist Then
                Else
                    ReDim Preserve Guilds(ct)
                    Guilds(ct) = ChInfo.Chara(i).Guild
                    ct += 1
                End If
            End If
        Next

        textGuild.Items.Clear()
        For i = 0 To ct - 1
            textGuild.Items.Add(Guilds(i))
        Next
        If textGuild.Items.Count > 0 Then
            textGuild.SelectedIndex = 0
        Else
            textGuild.Text = ""
            UpdateCharas(Realm, "", "", 0, Region)
        End If
    End Sub

    Private Sub UpdateCharas(ByVal Realm As String, ByVal Guild As String, ByVal ClassName As String, ByVal Level As Integer, ByVal Region As String)
        Dim ct = 0
        Dim i As Long
        For i = 0 To ChInfo.Chara.Length - 1
            If ChInfo.Chara(i).Region = Region And (ChInfo.Chara(i).Realm = Realm Or Realm = "") And (ChInfo.Chara(i).Guild = Guild Or Guild = "") And (ChInfo.Chara(i).ClassName = ClassName Or ClassName = "") And (ChInfo.Chara(i).Level >= Level Or Level <= 0) Then
                Dim j As Integer
                Dim exist As Boolean = False

                For j = 0 To ct - 1
                    If Charas(j) = ChInfo.Chara(i).Character Then
                        exist = True
                        Exit For
                    End If
                Next

                If exist Then
                Else
                    ReDim Preserve Charas(ct)
                    Charas(ct) = ChInfo.Chara(i).Character
                    ct += 1
                End If
            End If
        Next

        textCharacter.Items.Clear()
        For i = 0 To ct - 1
            textCharacter.Items.Add(Charas(i))
        Next
        If textCharacter.Items.Count > 0 Then
            textCharacter.SelectedIndex = 0
        Else
            textCharacter.Text = ""
        End If

        Try
            labelCharactersCount.Text = Format(Charas.Length, "###,##0") & " / " & Format(ChInfo.Chara.Length, "###,##0")
        Catch ex As Exception
            labelCharactersCount.Text = "no data"
        End Try
    End Sub

    Private Sub GetGuildData(ByVal Guild As String, ByVal Realm As String, ByVal Region As String)
        Dim c As String = textCharacter.Text
        Dim g As String = textGuild.Text
        Dim r As String = textRealm.Text
        Dim rg As String = textRegion.Text

        My.Application.DoEvents()
        ToolStripStatusLabel1.Text = "Access: " & Region & "/" & Realm & "/" & Guild

        My.Application.DoEvents()
        ChInfo.Filter = CreateFilterString()
        ChInfo.GetGuildMembersInfo(Guild, Realm, Region)

        Dim itv As Integer = ChInfo.UpdateInterval
        ChInfo.UpdateInterval = 365 * 100

        UpdateRealms(Region)

        GUI_UPDATING = True
        textRegion.Text = rg
        textRealm.Text = r
        textGuild.Text = ChInfo.GetCharactersInfo(c, r, rg).Guild
        textCharacter.Text = c
        ChInfo.UpdateInterval = itv
        GUI_UPDATING = False

        My.Application.DoEvents()
    End Sub

    Private Sub GetCharaData(ByVal Chara As String, ByVal Realm As String, ByVal Region As String)
        Dim c As String = textCharacter.Text
        Dim g As String = textGuild.Text
        Dim r As String = textRealm.Text
        Dim rg As String = textRegion.Text

        My.Application.DoEvents()
        ToolStripStatusLabel1.Text = "Access: " & Region & "/" & Realm & "/" & Chara

        My.Application.DoEvents()
        ChInfo.Filter = CreateFilterString()
        CurrentChara = ChInfo.GetCharactersInfo(Chara, Realm, Region)

        Dim itv As Integer = ChInfo.UpdateInterval
        ChInfo.UpdateInterval = 365 * 100

        UpdateRealms(Region)

        GUI_UPDATING = True
        textRegion.Text = rg
        textRealm.Text = r
        If g = "" Then
            textGuild.Text = g
        Else
            textGuild.Text = ChInfo.GetCharactersInfo(c, r, rg).Guild
        End If
        If CInt("0" & filterLevel.Text) > ChInfo.GetCharactersInfo(c, r, rg).Level Then
            filterLevel.Text = ""
        End If
        ChInfo.UpdateInterval = itv
        GUI_UPDATING = False

        textCharacter.Text = c

        My.Application.DoEvents()
    End Sub

    Private Sub GetAllData()
        Dim i As Long

        ChInfo.Filter = CreateFilterString()
        For i = 0 To ChInfo.Chara.Length - 1
            My.Application.DoEvents()
            ToolStripStatusLabel_Crawl.Text = "Updating All Chara Data (" & i + 1 & "/" & ChInfo.Chara.Length & ") " & ChInfo.Chara(i).Region & "/" & ChInfo.Chara(i).Realm & "/" & ChInfo.Chara(i).Character

            My.Application.DoEvents()
            CurrentChara = ChInfo.GetCharactersInfo(ChInfo.Chara(i).Character, ChInfo.Chara(i).Realm, ChInfo.Chara(i).Region)

            My.Application.DoEvents()
            ShowCharaData()
        Next

        'For i = 0 To ChInfo.Chara.Length - 1
        '    My.Application.DoEvents()
        '    ToolStripStatusLabel_Crawl.Text = "Updating All Guild Data (" & i + 1 & "/" & ChInfo.Chara.Length & ") " & ChInfo.Chara(i).Region & "/" & ChInfo.Chara(i).Realm & "/" & ChInfo.Chara(i).Guild

        '    My.Application.DoEvents()
        '    GetGuildData(ChInfo.Chara(i).Guild, ChInfo.Chara(i).Realm, ChInfo.Chara(i).Region)
        'Next

        ToolStripStatusLabel_Crawl.Text = ""
    End Sub

    Private Function CreateFilterString() As String
        Dim spcl As New WowCrawler.SpellAndClassDB

        Dim filter As String = ""

        If filterClass.Text = "" And filterLevel.Text = "" Then
            filter = ""
        ElseIf filterClass.Text = "" Then
            filter = "[@level>='" & filterLevel.Text & "']"
        ElseIf filterLevel.Text = "" Then
            filter = "[@classId='" & spcl.GetClassId(filterClass.Text) & "']"
        Else
            filter = "[@classId='" & spcl.GetClassId(filterClass.Text) & "' and @level>='" & filterLevel.Text & "']"
        End If

        Return filter
    End Function


    Private Sub textRegion_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles textRegion.SelectedIndexChanged
        UpdateRealms(textRegion.Text)
    End Sub

    Private Sub textRealm_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles textRealm.SelectedIndexChanged
        UpdateGuilds(textRealm.Text, textRegion.Text)
    End Sub

    Private Sub textGuild_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles textGuild.SelectedIndexChanged
        UpdateCharas(textRealm.Text, textGuild.Text, filterClass.Text, CInt("0" & filterLevel.Text), textRegion.Text)
    End Sub

    Private Sub filterClass_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles filterClass.SelectedIndexChanged
        UpdateCharas(textRealm.Text, textGuild.Text, filterClass.Text, CInt("0" & filterLevel.Text), textRegion.Text)
    End Sub

    Private Sub filterLevel_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles filterLevel.SelectedIndexChanged
        UpdateCharas(textRealm.Text, textGuild.Text, filterClass.Text, CInt("0" & filterLevel.Text), textRegion.Text)
    End Sub

    Private Sub buttonUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles buttonUpdate.Click
        UpdateData()
    End Sub

    Private Sub UpdateData()
        If textCharacter.Text <> "" Then
            If textCharacter.Text.Length = 1 Then
                textCharacter.Text = UCase(textCharacter.Text)
            ElseIf textCharacter.Text.Length >= 2 Then
                textCharacter.Text = UCase(Mid(textCharacter.Text, 1, 1)) & LCase(Mid(textCharacter.Text, 2))
            End If

            GetCharaData(textCharacter.Text, textRealm.Text, textRegion.Text)

            CurrentChara = ChInfo.GetCharactersInfo(textCharacter.Text, textRealm.Text, textRegion.Text)
            ShowCharaData()
        Else
            If textGuild.Text <> "" Then
                GetGuildData(textGuild.Text, textRealm.Text, textRegion.Text)
            End If
        End If
        ChInfo.SaveArmoryData()
    End Sub

    Private Sub buttonUpdateAll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles buttonUpdateAll.Click
        GetAllData()
        ChInfo.SaveArmoryData()
    End Sub

    Private Sub textCharacter_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles textCharacter.SelectedIndexChanged

        My.Application.DoEvents()
        ToolStripStatusLabel1.Text = "Access: " & textRegion.Text & "/" & textRealm.Text & "/" & textCharacter.Text
        My.Application.DoEvents()

        CurrentChara = ChInfo.GetCharactersInfo(textCharacter.Text, textRealm.Text, textRegion.Text)

        ShowCharaData()
    End Sub

    Private Sub ShowCharaData()
        chkReject.Checked = CurrentChara.Rejected
        txtAka.Text = CurrentChara.AkaChara

        lblCurrentChara.Text = CurrentChara.Character & ", " & CurrentChara.Region & "/" & CurrentChara.Realm & "/" & CurrentChara.Guild

        Dim CIV As New WowCrawler.CharaInfoViewer
        Dim html(0) As String
        Dim filename As String

        If chkSimpleText.Checked Then
            html(0) = CIV.CharaInfoToStr(CurrentChara)
            filename = My.Computer.FileSystem.CombinePath(My.Computer.FileSystem.SpecialDirectories.Temp, "armoryviewtemp.txt")
        Else
            html(0) = CIV.CharaInfoToHtml(CurrentChara, False)
            filename = My.Computer.FileSystem.CombinePath(My.Computer.FileSystem.SpecialDirectories.Temp, "armoryviewtemp.html")
        End If

        Try
            System.IO.File.WriteAllLines(filename, html, System.Text.Encoding.UTF8)
        Catch ex As Exception
        End Try

        WebBrowser1.Navigate(filename)
    End Sub

    Private Sub ShowGuildData(ByVal Region As String, ByVal Realm As String, ByVal Guild As String)
        lblCurrentChara.Text = CurrentChara.Region & "/" & CurrentChara.Realm & "/" & CurrentChara.Guild

        Dim CIV As New WowCrawler.CharaInfoViewer
        Dim path As String = ""

        'path = My.Computer.FileSystem.SpecialDirectories.Temp
        path = My.Computer.FileSystem.CombinePath(RosterFolder, Guild)
        My.Computer.FileSystem.CreateDirectory(path)

        CIV.GuildRosterToHtml(Region, Realm, Guild, ChInfo, False, path, RosterRaidVersionFilter)

        WebBrowser1.Navigate(My.Computer.FileSystem.CombinePath(path, "index.html"))
    End Sub

    Private Sub textUpdateInterval_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles textUpdateInterval.SelectedIndexChanged
        ChInfo.UpdateInterval = CInt(textUpdateInterval.Text)
    End Sub

    Dim isCrawling As Boolean = False
    Private Sub buttonAutoPilot_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles buttonAutoPilot.Click
        Crawl()
    End Sub

    Private Sub Crawl()
        If textAutoPilotList.Text = "" Then Exit Sub

        If isCrawling Then
            isCrawling = False
            Exit Sub
        End If

        isCrawling = True

        Dim lists() As String
        lists = Split(textAutoPilotList.Text, vbCrLf)

        Dim delimiter As String = vbTab
        If InStr(textAutoPilotList.Text, "/") Then
            delimiter = "/"
        ElseIf InStr(textAutoPilotList.Text, ",") Then
            delimiter = ","
        End If

        Dim i As Integer
        Dim entry() As String
        Dim xmltext As String = ""
        For i = 0 To lists.Length - 1
            entry = Split(lists(i), delimiter)
            If entry.Length >= 3 Then
                My.Application.DoEvents()
                ToolStripStatusLabel_Crawl.Text = "Crawling (" & i + 1 & "/" & lists.Length & ") " & entry(2) & "/" & entry(1) & "/" & entry(0)

                My.Application.DoEvents()
                GetGuildData(entry(2), entry(1), entry(0))
            End If
        Next
        isCrawling = False

        ToolStripStatusLabel_Crawl.Text = ""
        ChInfo.SaveArmoryData()
    End Sub

    Dim spdis As Integer = 300
    Private Sub Form1_ResizeBegin(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.ResizeBegin
        spdis = SplitContainer1.SplitterDistance
    End Sub

    Private Sub Form1_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize
        SplitContainer1.SplitterDistance = spdis
    End Sub

    Private Sub Form1_ResizeEnd(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.ResizeEnd
        SplitContainer1.SplitterDistance = spdis
    End Sub

    Private Sub btnApply_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnApply.Click
        If GUI_UPDATING = False And textCharacter.Text <> "" Then
            ChInfo.SetRejectCharacter(chkReject.Checked, textCharacter.Text, txtAka.Text)
        End If
    End Sub

    Private Sub btnAddQueue_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddQueue.Click
        AddQueue()
    End Sub

    Private Sub AddQueue()
        If textRegion.Text <> "" And textRealm.Text <> "" And textGuild.Text <> "" Then
            Dim queueTxt As String = textRegion.Text & "/" & textRealm.Text & "/" & textGuild.Text

            If textAutoPilotList.Text = "" Then
                textAutoPilotList.Text = queueTxt
            Else
                textAutoPilotList.Text = queueTxt & vbCrLf & textAutoPilotList.Text
            End If
        End If
    End Sub

    Private Sub MenuUpdateAll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuUpdateAll.Click
        GetAllData()
        ChInfo.SaveArmoryData()
    End Sub

    Private Sub MenuUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuUpdate.Click
        UpdateData()
    End Sub

    Private Sub MenuQueue_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuQueue.Click
        AddQueue()
    End Sub

    Private Sub MenuQueueClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuQueueClear.Click
        textAutoPilotList.Text = ""
    End Sub

    Private Sub MenuVerInfo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuVerInfo.Click
        MsgBox("(@_@b", MsgBoxStyle.OkOnly, "About Blue Forest...")
    End Sub

    Private Sub MenuQuit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuQuit.Click
        End
    End Sub

    Private Sub MenuCrawl_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuCrawl.Click
        Crawl()
    End Sub

    Private Sub MenuRoster_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuRoster.Click
        ShowGuildData(CurrentChara.Region, CurrentChara.Realm, CurrentChara.Guild)
    End Sub
End Class
